# -*- coding: utf-8 -*-
# This code written by ChanGOGOGO
"""
模拟蘑菇云回调callplus
"""
import logging
import os
import time
from util import get_now_time, post_json


def push_receive_report(session_id, phone, status="0"):
    """
    模拟蘑菇向callplus推送短信接收状态报告
    :param session_id:
    :param phone:
    :param status: 0-成功，1-失败
    :return:
    """
    status_str = str(status)
    if status_str == "0":
        desc = "DELIVRD"
    else:
        desc = "UNDELIV"
    now_time = get_now_time()
    req = [
        {
            "appkey": "zhuiyi",
            "desc": desc,
            "phone": phone,
            "report_time": now_time,
            "status": status_str,
            "uid": session_id,
        }
    ]
    url = "http://172.18.160.132:8085/sms/receive/moguyun"
    res = post_json(url, req)
    return res


def push_replay_report(phone, extend):
    """
    模拟蘑菇向callplus推送短信上行
    :param phone: 手机号
    :param extend: 扩展号
    :return:
    """
    now_time = get_now_time()
    msg = f"上行回复-{now_time}"
    req = [
        {
            "appkey": "zhuiyi",
            "phone": phone,
            "msg": msg,
            "extend": extend,
            "deliver_time": now_time,
        }
    ]
    url = "http://172.18.160.132:8085/sms/replay/moguyun"
    res = post_json(url, req)
    return res


def auto_push(record_dir):
    """自动推送短信接收状态报告和上行"""
    sms_supplier_status = {"a": "1", "b": "0", "c": "0"}
    file_names = os.listdir(record_dir)
    for file_name in file_names:
        file_path = os.path.join(record_dir, file_name)
        sms_supplier_name = file_name.split(".")[0]  # 根据文件名得到短信供应商名
        send_status = sms_supplier_status.get(
            sms_supplier_name
        )  # 每个短信供应商返回固定的短信发送状态
        with open(file_path) as file:
            contents = file.readlines()
        for content in contents:
            content = content.replace("\n", "")
            content_split = content.split(",")
            _, uid, phone, extend, session_id = content_split
            push_receive_report(session_id, phone, send_status)
            if send_status == "0":
                time.sleep(3)
                push_replay_report(phone, extend)
        # 删除文件
        if os.path.exists(file_path):
            os.remove(file_path)
        else:
            logging.info(f"{file_path}文件不存在！")


def get_now_time() -> str:
    """
    获取当前时间，格式为YYYY-mm-dd HH:MM:SS
    :return: 当前时间
    """
    not_time = time.strftime("%Y-%m-%d %H:%M:%S")
    return not_time


if __name__ == "__main__":
    t_record_dir = "./txt"
    auto_push(t_record_dir)
